package 热题100;

public class 热题34在排序数组中查找元素的第一个和最后一个位置 {
    public static void main(String[] args) {

    }


    public int[] searchRange(int[] nums, int target) {

        if (nums == null || nums.length == 0){
            return new int[]{-1,-1};
        }

        int index = help(nums,target,0,nums.length-1);

        int l = index,r= index+1;

        if(l == -1){
            return new int[]{-1,-1};
        }
        while (l >= 0 && nums[l] == target){
            l--;
        }
        l++;
        while (r <= nums.length-1 && nums[r] == target){
            r++;
        }
        r--;

        int[] res = {l,r};
        return res;
    }

    private int help(int[] nums, int target, int l, int r) {
        if (l >= 0 && l <= nums.length-1 && nums[l] == target){
            return l;
        }
        if (r <= nums.length - 1 && r >= 0 && nums[r] == target){
            return r;
        }
        if (l >= r){
            return -1;
        }

        int mid = (l + r) >> 1;

        if (nums[mid] < target){
            return help(nums,target,mid + 1,r);
        }else if (nums[mid] > target){
            return help(nums,target,l,mid);
        }else {
            return mid;
        }
    }
}
